package com.web.expspringboot.service.hustImpl;

import com.web.expspringboot.entity.CartSt;
import com.web.expspringboot.entity.ProductSt;
import com.web.expspringboot.mapper.CartMapper;
import com.web.expspringboot.service.CartService;
import com.web.expspringboot.service.PurchaseService;
import com.web.expspringboot.service.ProductService;
import com.web.expspringboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Profile("hust")
public class CartServiceImpl implements CartService {

    @Autowired
    CartMapper cartMapper;

    @Autowired
    ProductService productService;

    @Autowired
    UserService userService;

    @Autowired
    PurchaseService messageService;

    @Override
    public List<CartSt> getCart() {
        Long userId = userService.getSessionUserId();
        if (userId == null) {
            return null;
        }
        return cartMapper.selectCartByUserId(userId);
    }

    @Override
    public boolean addCart(long productId) {
        Long userId = userService.getSessionUserId();
        if (userId == null) {
            return false;
        }
        CartSt cart = new CartSt();
        cart.setUserId(userId);
        cart.setProductId(productId);
        return cartMapper.insertCart(cart) > 0;
    }

    @Override
    public boolean deleteCart(long productId) {
        Long userId = userService.getSessionUserId();
        if (userId == null) {
            return false;
        }
        return cartMapper.deleteCart(userId, productId) > 0;
    }

    @Override
    public int purchaseProduct(long productId) {
        Long userId = userService.getSessionUserId();
        if (userId == null) {
            return -1;
        }
        if (cartMapper.purchaseProduct(userId, productId) >= 0){
            int result = messageService.addNewPurchase(productId, userId);
            if (result == 0){
                productService.updateProductStatus(productId, 2);
            }
            return result;
        }
        return -1;
    }

    @Override
    public List<ProductSt> getCartProducts() {
        Long userId = userService.getSessionUserId();
        return cartMapper.getCartProducts(userId);
    }
}
